package com.gzone.contentprovider;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.gzone.contentprovider.helper.RequestMethod;
import com.gzone.contentprovider.helper.RestClient;
import com.gzone.contentprovider.sql.model.Category;
import com.gzone.contentprovider.sql.model.Item;
import com.gzone.contentprovider.sql.service.DatabaseServices;
import com.gzone.contentprovider.utils.HTTPClientUtil;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.AdapterView.OnItemSelectedListener;

public class ContentProviderActivity extends Activity {
    private static final String TAG = "ContentProviderActivity";
	private RestClient requestItem;
	private ArrayList<Item> listItem;
	private DatabaseServices service;
	private ArrayList<Category> listCat;
	private Spinner spinner;
	protected int currentId;
	private ProgressDialog progress;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button button = (Button) findViewById(R.id.button_go_toList);
        button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				goToListItem();
			}
		});
        spinner = (Spinner) findViewById(R.id.spinner_list_category);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				Log.i(TAG, "--->" + position + ", " + listCat.get(position).title);
				currentId = listCat.get(position).id;
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
        progress = new ProgressDialog(this, android.R.style.Widget_ProgressBar);
//        progress.setTitle("Downloading...");
        progress.setMessage("Loading...");
        progress.show();
        new DemoTask().execute(null);
    }
    
    protected void goToListItem() {
		// TODO Auto-generated method stub
		Intent intent = new Intent(this, ActivityManager.class);
		intent.putExtra("CategoryId", currentId);
		startActivity(intent);
	}

	class DemoTask extends AsyncTask<String, Boolean, Void> {

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
			requestItem();
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			showData();
		}
    	
    }
	
	private void showProgress(){
		final Handler handler = new Handler();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				handler.post(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						progress.show();
					}
				});
			}
		}).start();
	}

	public void requestItem() {
//		requestItem = new RestClient("http://91.121.156.153/~services/json.php");
//		requestItem.AddParam("op", "g");
//		requestItem.AddParam("t", "item");
//		try {
//			requestItem.Execute(RequestMethod.GET);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		RestClient requestCategory = new RestClient("http://91.121.156.153/~services/json.php");
//		requestCategory.AddParam("op", "g");
//		requestCategory.AddParam("t", "category");
//		try {
//			requestCategory.Execute(RequestMethod.GET);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		String dataCategory = "";
		try {
			 dataCategory = HTTPClientUtil.getString("http://91.121.156.153/~services/json.php?op=g&t=category");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		dataCategory = dataCategory.trim();
		if(dataCategory.endsWith(";")){
			dataCategory = dataCategory.substring(0, dataCategory.length()-1);
		}
		
		dataCategory = dataCategory.replaceAll("\n", " ");
		dataCategory = dataCategory.replace("\r", " ");
		
		String dataItem = "";
		String url = "http://91.121.156.153/~services/json.php?op=g&t=item";
		try {
			dataItem  = HTTPClientUtil.getString(url);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		dataItem = dataItem.trim();
		if(dataItem.endsWith(";")){
			dataItem = dataItem.substring(0, dataItem.length()-1);
		}
		
		dataItem = dataItem.replaceAll("\n", " ");
		dataItem = dataItem.replace("\r", " ");
		System.out.println("---> test '" + dataItem + "'");
//		System.out.println("---> test '" + dataItem.substring(258, 268)+"'");
//		dataItem = dataItem.replace("};", "}");
//		dataItem = dataItem.replace("</p>", "");
		service = DatabaseServices.getInstance(this);
//		service.insertDBTest();
		service.synchronizeCategory(dataCategory);
		service.synchronizeItem(dataItem);
//		service.synchronizeDB(dataItem, dataCategory);
		/*RestClient requestHit = new RestClient("http://91.121.156.153/~services/json.php");
		requestHit.AddParam("op", "g");
		requestHit.AddParam("t", "hit");
		try {
			requestHit.Execute(RequestMethod.GET);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			JSONObject hit = new JSONObject(requestHit.getResponse());
			JSONArray arr = hit.getJSONArray("hit");
//			for(int i =0; i < arr.length(); i++)
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
	}
	void displayEvents() {
	}

	public void showData() {
		// TODO Auto-generated method stub
		listCat = service.getAllCategory();
		String cateName[] = new String[listCat.size()];
		for(int i = 0; i < listCat.size(); i ++){
			cateName[i] = listCat.get(i).title;
		}
		
		ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, cateName);
		spinner.setAdapter(adapter);
		progress.dismiss();
//		Log.i(TAG, "------>Cate" + listCat.size());
//		listItem = service.getAllItem();
//		Log.i(TAG, "------>Item" + listItem.size());
//		for(Item item : listItem){
//			Log.i(TAG, "------>" + item.title + "/" + item.desc);
//		}
	}
	
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		service = DatabaseServices.getInstance(this);
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		service.destroy();
		super.onDestroy();
	}
}